<script setup>
import { reactive, useTemplateRef, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { handleLogger } from '@renderer/util/common'

const show = defineModel('show', { type: Boolean, default: false })
const emits = defineEmits(['success'])

const props = defineProps({
  editItemData: {
    type: [null, Object],
    default: null
  }
})

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  levelOpts.value = res
}
watch(
  () => show.value,
  (n) => {
    if (n) {
      handleGetLevelOpts()
      formState.level = props.editItemData.dealer_level_id
    }
  }
)
const formRules = {
  level: [{ required: true, message: '请选择经销商等级', trigger: 'change' }]
}
const formState = reactive({
  level: ''
})
const formRef = useTemplateRef('formRef')
async function handleConfirm() {
  formRef.value.validate()
  let levelName = ''
  levelOpts.value.forEach((item) => {
    if (item.dealer_level_id === formState.level) {
      levelName = item.dealer_level_name
    }
  })
  const res = await window.api.updateDealerLevel(
    formState.level,
    levelName,
    props.editItemData.dealer_id
  )
  console.log(res)
  handleLogger(`调整${props.editItemData.dealer_name}等级为${levelName}`)
  ElMessage.success('修改成功')
  emits('success')
  show.value = false
}
</script>

<template>
  <el-dialog v-model="show" width="500" title="调整等级" draggable>
    <el-form ref="formRef" :model="formState" :rules="formRules" label-width="100px">
      <el-form-item label="经销商等级" prop="level">
        <el-select v-model="formState.level" placeholder="请选择等级">
          <el-option
            v-for="item in levelOpts"
            :key="item.dealer_level_id"
            :label="item.dealer_level_name"
            :value="item.dealer_level_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经销商名称">
        <el-input disabled :value="props.editItemData?.dealer_name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
